import Dep from './dep'
class Observer{
    constructor (data) {
        this.walk(data)
    }
    walk (data) {
            // data 是否是对象 
            if(!data || typeof data !== 'object'){
                return
            }
        Object.keys(data).forEach( d => {
            this.defineReactive(data,d, data[d])
        })
    }

    defineReactive (obj, key, val) {
        let that = this
        //收集依赖发送通知
        let dep = new Dep()
        // val 是obj 转换内部属性城响应式
        this.walk(val)
        Object.defineProperty(obj,key,{
            enumerable:true,
            configurable:true,
            get() {
                Dep.target && dep.addSub(Dep.target)
                return val
            },
            set (newValue){
                if(newValue == val){
                    return
                }
                val = newValue
                that.walk(newValue)
                dep.notify()
            }
        })
    }
}

export default Observer